package com.snsoft.luxurywallpaper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;


public class LuxuryWallpaperDetail extends Activity {
	private WebView wv;
	private Dialog dialog;
	private String wvurl = "";
    public ProgressDialog mProgressDialog;
    public File f; 
	private String param = "";

	private String actiontype;
	
	private static final int SELECT_IMAGE = 100;
	private static final int DIALOG_WALLPAPER_PROGRESS = 2;
	private static final int DIALOG_QUIT_ALERT = 1;
	private static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Activity activity = this; 
        
        Bundle extras = getIntent().getExtras();
        final String detail_url = extras.getString("DETAIL_URL");
        final String name = extras.getString("NAME");
        
        setContentView(R.layout.detail);
        
        wv = (WebView)findViewById(R.id.wvdetail);
        
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setLoadsImagesAutomatically(true);
        wv.getSettings().setLightTouchEnabled(true);
        wv.getSettings().setPluginsEnabled(true);
        wv.setHorizontalScrollBarEnabled(false);
        wv.setVerticalScrollbarOverlay(true);

        wv.setBackgroundColor(Color.BLACK);
        
        // Loading dialog set
        dialog = new Dialog(this, R.style.SNDialog);
        dialog.addContentView(new ProgressBar(this), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        
        wv.setWebViewClient(new WebViewClient()
        {
        	// Webview handler
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		actiontype = url;
    			String sd = Environment.getExternalStorageDirectory().toString();
				File path = new File(sd + "/LuxuryWallpaper");
				
				
				if(url.startsWith("http://wallpaper") || url.startsWith("http://save") || url.startsWith("http://share"))
        		{
					String pcsurl = url.substring(url.indexOf("#") + 1);
        			Log.d("URL:", pcsurl);
        			String pcsfn = pcsurl.substring(pcsurl.lastIndexOf("/") + 1);
        			Log.d("FILE:", pcsfn);
    				File fnnew = new File(sd + "/LuxuryWallpaper", pcsfn);
    				
    				if(!path.isDirectory()) 
    				{
    					path.mkdirs();
    				}
    				
        			if(fnnew.isFile())
    				{
        				if(url.startsWith("http://save"))
    						Toast.makeText(activity, "The same file already exists.", Toast.LENGTH_LONG).show();
    					else if(url.startsWith("http://share"))
    						onShare(fnnew);
    					else
    						new DownloadFileAsync().execute(pcsurl, pcsfn);
    				}
    				else
    				{
    					new DownloadFileAsync().execute(pcsurl, pcsfn);
    				}
        		}
        		else if(url.startsWith("http://send"))
				{
        			String action = Intent.ACTION_PICK;
        	        Uri uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        	        Intent itGallery = new Intent(action, uri);
        	        startActivityForResult(itGallery, SELECT_IMAGE);
				}
        		else if(url.startsWith("http://close"))
        		{
        			overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
        			LuxuryWallpaperDetail.this.finish();
        		}
        		else
        			view.loadUrl(url);
				
        		return true;
        	}
        	
        	
        	@Override     
        	public void onPageStarted(WebView view, String url, Bitmap favicon) 
        	{
        		dialog.show();
        	} 
        	
        	@Override     
        	public void onPageFinished(WebView view, String url) 
        	{        		
        		wvurl = wv.getUrl();		// 전역변수사용
        		
        		if(dialog.isShowing())
        		{
        			dialog.dismiss();
        		}
        		
        		view.loadUrl("javascript:Load('" + detail_url + "', '" + name + "')");
        		param = "";
        	}

        	@Override
        	public void onReceivedError(WebView view, int errorCode,String description, String failingUrl)
        	{
        		wv.loadData("<html><body align='center' valign='center'></body></html>", "text/html", "UTF-8");
        		Toast.makeText(activity, "Network unavailable. Please try again later.", Toast.LENGTH_LONG).show();
        	}
        });
        
        wv.loadUrl("file:///android_asset/sub_info.html");
        
    }

    // Screen rotating fix
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }
    
    @Override
	public void onDestroy() {
		super.onDestroy();
	}
    
    // Wallpaper
    public void onWallpaper(File fn)
    {
    	// 폰의 화면 사이즈를 구한다.
        Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int displayHeight = display.getHeight();
        
    	final WallpaperManager wm = (WallpaperManager)this.getSystemService("wallpaper");

    	try 
		{
    		Bitmap bmp = BitmapFactory.decodeFile(fn.getAbsolutePath());
    		int i = (int)getBestImageWidth(bmp, displayHeight);
    		wm.suggestDesiredDimensions(i, displayHeight);
    		Bitmap localBitmap = Bitmap.createScaledBitmap(bmp, i, displayHeight, true);

            wm.setBitmap(localBitmap);
			Toast.makeText(getApplicationContext(), "Saved.", Toast.LENGTH_LONG).show();
			
		} catch (OutOfMemoryError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    }
    
    private double getBestImageWidth(Bitmap paramBitmap, int dispheight)
    {
      double d = paramBitmap.getHeight();
      return paramBitmap.getWidth() * (dispheight / d);
    }
    
    
    private void setWallpaperDimension() 
    {
    	 WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);

    	 Display display = getWindowManager().getDefaultDisplay();
    	 boolean isPortrait = display.getWidth() < display.getHeight();
    	 final int width = isPortrait ? display.getWidth() : display.getHeight();
    	 final int height = isPortrait ? display.getHeight() : display.getWidth();
    	 wpm.suggestDesiredDimensions(width * 1, height);
    }
    
    // Share
    public void onShare(File fn)
    {
    	Intent itShare = new Intent(Intent.ACTION_SEND);
		MimeTypeMap type = MimeTypeMap.getSingleton();
		itShare.setType(type.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(fn.toString())));
		itShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fn));
		itShare.putExtra(Intent.EXTRA_TEXT, "[Copyright]LuxuryWallpaper"); 
		startActivity(itShare);
    }
    
    // Image Download
    class DownloadFileAsync extends AsyncTask<String, String, String> 
    {
        
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			
			if(actiontype.startsWith("http://wallpaper"))
				showDialog(DIALOG_WALLPAPER_PROGRESS);
			else
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

        @Override
        protected String doInBackground(String... aurl) 
        {
            int count;

            try 
            {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                
                String sd = Environment.getExternalStorageDirectory().toString();
                
				File path = new File(sd + "/LuxuryWallpaper");
				
				if(!path.isDirectory()) 
				{
					path.mkdirs();
				}
       	     
    			String fn = aurl[1];
    			f = new File(path, fn);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(f.getAbsolutePath());

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) 
                {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            return null;

        }
        
        protected void onProgressUpdate(String... progress) 
        {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) 
        {
        	dialog.dismiss();
        	
            
        	if(actiontype.startsWith("http://wallpaper"))
        	{
        		onWallpaper(f);
        		removeDialog(DIALOG_WALLPAPER_PROGRESS);
        	}
        	if(actiontype.startsWith("http://save"))
        	{
        		Toast.makeText(getApplicationContext(), "Saved.", Toast.LENGTH_LONG).show();
        		removeDialog(DIALOG_DOWNLOAD_PROGRESS);
        	}
        	else if(actiontype.startsWith("http://share"))
        	{
        		removeDialog(DIALOG_DOWNLOAD_PROGRESS);
        		onShare(f);
        	}
        }
    }
    
    
    
    // Dialog Management
    @Override
    protected Dialog onCreateDialog(int id) 
    {
    	super.onCreateDialog(id);
    	
        switch (id) 
        {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Saving..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                return mProgressDialog;
            case DIALOG_WALLPAPER_PROGRESS:
            	mProgressDialog = ProgressDialog.show(this, "", "Setting wallpaper,please wait...", true);
            	return mProgressDialog;
            default:
                return null;
        }
    }
    
    /**
     * 지정한 패스의 파일을 읽어서 Bitmap을 리턴 (화면사이즈에 최다한 맞춰서 리스케일한다.)
     *
     * @param context
     *            application context
     * @param imgFilePath
     *            bitmap file path
     * @return Bitmap
     * @throws IOException
     */
   public static Bitmap loadBackgroundBitmap(Context context, String imgFilePath) throws Exception, OutOfMemoryError 
   { 
       // 폰의 화면 사이즈를 구한다.
       Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
       int displayWidth = display.getWidth();
       int displayHeight = display.getHeight();
       
       // 읽어들일 이미지의 사이즈를 구한다.
       BitmapFactory.Options options = new BitmapFactory.Options();
       options.inPreferredConfig = Config.RGB_565;
       options.inJustDecodeBounds = true;
       BitmapFactory.decodeFile(imgFilePath, options);
    
       // 화면 사이즈에 가장 근접하는 이미지의 리스케일 사이즈를 구한다.
       // 리스케일의 사이즈는 짝수로 지정한다. (이미지 손실을 최소화하기 위함.) 
       float widthScale = options.outWidth / displayWidth;
       float heightScale = options.outHeight / displayHeight;
       float scale = widthScale > heightScale ? widthScale : heightScale;
               
       if(scale >= 8) {
           options.inSampleSize = 8;
       } else if(scale >= 6) {
           options.inSampleSize = 6;
       } else if(scale >= 4) {
           options.inSampleSize = 4;
       } else if(scale >= 2) {
           options.inSampleSize = 2;
       } else {
           options.inSampleSize = 1;
       }
       options.inJustDecodeBounds = false;
    
       return BitmapFactory.decodeFile(imgFilePath, options);
   }
   
 //URL을 이용해서 이미지 다운로드 하기
   private Bitmap GetImageFromURL(String strImageURL) 
   {
       Bitmap imgBitmap = null;
       
       try
       {
       	URL url = new URL(strImageURL);
       	URLConnection conn = url.openConnection();
       	conn.connect();
       	
       	int nSize = conn.getContentLength();
       	BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), nSize);
       	imgBitmap = BitmapFactory.decodeStream(bis);
       	
       	bis.close();
       }
       catch (Exception e)
       {
       	e.printStackTrace();
       }
       
       return imgBitmap;
   }
   
   static public Bitmap BitmapSizeChange(Bitmap wbitmap , int width , int height)
   {
           int wwidth = wbitmap.getWidth();
           int wheight = wbitmap.getHeight();
           int newWidth = width;
           int newHeight =height;
    
           float scalewidth = ((float)newWidth)/wwidth;
           float scaleheight = ((float)newHeight) / wheight;
    
           Matrix mt = new Matrix();
           mt.postScale(scalewidth, scaleheight);
    
           Bitmap resizebt = Bitmap.createBitmap(wbitmap , 0 , 0, wwidth , wheight , mt , true);
           mt = null;
           return resizebt;
   } 
   
   @Override
   public void onBackPressed() 
   {
	   overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

	   LuxuryWallpaperDetail.this.finish();
	   
   }
}